go to previous page   go to home page   go to next page
double A= 123.1, B= -1.1;
DecimalFormat numform = new DecimalFormat(" ##0.###;-##0.###"); 
System.out.println( "A = " + numform.format(A) );
System.out.println( "B = " + numform.format(B) );

Answer:

A =  123.1
B = -1.1

Using just one Pattern

If you are using #, there is usually little benefit in also using a subpattern for negative numbers. Find a pattern that works well for the range of numbers you expect to write.

The format pattern ###0.0### works well for typical floating point numbers. Add more #s on the left for larger numbers or on the right for greater accuracy. The pattern ###0 works well for typical integers.


QUESTION 15:

(Trick Question: ) What does the following fragment write:

int A= 12, B= -456;

DecimalFormat numform = new DecimalFormat("###0.0###"); 

System.out.println( "A = " + numform.format(A) );  
System.out.println( "B = " + numform.format(B) );  

Hint: what types are the variables?